package com.mw.job.zookeeper;

import com.mw.job.bean.AppProperties;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * Created by mengdexuan on 2017/9/30 14:31.
 */
public class ZkClient {

	private static Logger log = LoggerFactory.getLogger(ZkClient.class);

	private static final String ROOT_NODE = "/MW-JOB";

	private static ZooKeeper zooKeeper = null;

	public static void connect(String connectString, int sessionTimeout,AppProperties appProperties) {
		try {
			zooKeeper = new ZooKeeper(connectString, sessionTimeout, new ZkWatch());
			log.info("初始化 zk 连接！");
			initNode(ROOT_NODE,ROOT_NODE);
			String key = ROOT_NODE+"/"+appProperties.getKey();
			initNode(key,appProperties.getDescription());
			initNode(key+"/lock","");
			initNode(key+"/node","");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("初始化 zk 连接失败！", e);
		}
	}

	private static void initNode(String nodePath,String nodeVal){
		try {
			if (zooKeeper.exists(nodePath, true) == null) {
				String node = null;
				node = zooKeeper.create(nodePath,
						nodeVal.getBytes(Charset.forName("UTF-8")),
						ZooDefs.Ids.OPEN_ACL_UNSAFE,
						CreateMode.PERSISTENT);
				log.info("创建初始节点 --> nodePath: "+node+", nodeVal: " + nodeVal);
			}else {
				zooKeeper.setData(nodePath,nodeVal.getBytes(Charset.forName("UTF-8")),-1);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}


	public static void createNode(String nodePath,String nodeVal,CreateMode mode){
		try {
			if (zooKeeper.exists(nodePath, true) == null) {
				String node = null;
				node = zooKeeper.create(nodePath,
						nodeVal.getBytes(Charset.forName("UTF-8")),
						ZooDefs.Ids.OPEN_ACL_UNSAFE,
						mode);
				log.info("节点创建成功 --> nodePath: "+node+", nodeVal: " + nodeVal);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public static ZooKeeper client() {
		return zooKeeper;
	}

	public static void close() {
		if (zooKeeper != null) {
			try {
				zooKeeper.close();
			} catch (InterruptedException e) {
			}
		}
	}

}
